package com.ruoyi.crm.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.crm.domain.*;
import com.ruoyi.crm.domain.dos.ContractData;
import com.ruoyi.crm.domain.dos.ContractDos;
import com.ruoyi.crm.domain.dos.SubjectGroupNumDos;
import com.ruoyi.crm.domain.dto.ContractDTO;
import com.ruoyi.crm.domain.vo.ContractStatisticsVO;
import com.ruoyi.crm.domain.vo.ContractVO;
import com.ruoyi.crm.enums.DiscountType;
import com.ruoyi.crm.enums.StatusType;
import com.ruoyi.crm.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.crm.mapper.ContractMapper;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import static com.ruoyi.common.utils.DateUtils.getTwoDaysDayDes;

/**
 * 合同管理Service业务层处理
 *
 * @author ruoyi
 * @date 2022-06-07
 */
@Service
@Slf4j
@Transactional
public class ContractServiceImpl implements IContractService {
	@Autowired
	private ContractMapper contractMapper;
	@Resource
	private IBusinessService iBusinessService;
	@Resource
	private IActivityService iActivityService;
	@Resource
	private ICourseService iCourseService;

	/**
	 * 查询合同管理
	 *
	 * @param id 合同管理主键
	 * @return 合同管理
	 */
	@Override
	public Contract selectContractById(String id) {
		return contractMapper.selectContractById(id);
	}

	@Override
	public List<Contract> selectContractList(Contract contract) {
		return contractMapper.selectContractList(contract);
	}

	/**
	 * 查询合同管理列表
	 *
	 * @param contract 合同管理
	 * @return 合同管理
	 */
	@Override
	public List<ContractVO> selectContractVOList(Contract contract) {
		List<Contract> contracts = contractMapper.selectContractList(contract);

		List<ContractVO> contractVOS = new ArrayList<>();
		contracts.forEach(c -> {
			ContractVO contractVO = new ContractVO();
			BeanUtils.copyProperties(c, contractVO);
			if (Objects.nonNull(c.getContractOrder())) {
				contractVO.setOrder(c.getContractOrder().doubleValue());
			}
			if (Objects.nonNull(c.getActivityId())) {
				contractVO.setActivityId(c.getActivityId().intValue());
			}
			if (Objects.nonNull(c.getCoursePrice())) {
				contractVO.setCoursePrice(c.getCoursePrice().intValue());
			}
			contractVO.setCreateTime(c.getCreateTime());
			contractVOS.add(contractVO);
		});
		return contractVOS;
	}

	/**
	 * 新增合同管理
	 *
	 * @param contract 合同管理
	 * @return 结果
	 */
	@Override
	public int insertContract(Contract contract) {
		log.info("insertContract.contract：{}",contract);

		LoginUser loginUser = SecurityUtils.getLoginUser();
		contract.setCreateTime(DateUtils.getNowDate());
		contract.setId(UUID.randomUUID(true).toString());
		contract.setDeptId(loginUser.getDeptId());
		contract.setCreateBy(loginUser.getUsername());

		Course course = iCourseService.selectCourseById(contract.getCourseId());
		contract.setCourseName(course.getName());
		contract.setStatus("1");
		contract.setCoursePrice(course.getPrice().floatValue());
		contract.setProcessInstanceId(IpUtils.getHostIp());

		Activity activity = iActivityService.selectActivityById(contract.getActivityId());
		contract.setActivityName(activity.getName());
		if (Objects.nonNull(activity.getId())) {
			contract.setActivityName(activity.getName());
			//折扣
			Float discount = activity.getDiscount();
			//代金券
			Integer vouchers = activity.getVouchers();
			if (Objects.nonNull(discount)) {
				contract.setContractOrder(contract.getCoursePrice() * discount);
				contract.setDiscountType(DiscountType.CLASS_ACTIVITY.getVal());
			} else if (Objects.nonNull(vouchers)) {
				contract.setContractOrder(contract.getCoursePrice().floatValue() - vouchers);
				contract.setDiscountType(DiscountType.VOUCHER.getVal());
			}
		}
		return contractMapper.insertContract(contract);
	}

	/**
	 * 修改合同管理
	 *
	 * @param contract 合同管理
	 * @return 结果
	 */
	@Override
	public int updateContract(Contract contract) {
		return contractMapper.updateContract(contract);
	}

	/**
	 * 批量删除合同管理
	 *
	 * @param ids 需要删除的合同管理主键
	 * @return 结果
	 */
	@Override
	public int deleteContractByIds(String[] ids) {
		return contractMapper.deleteContractByIds(ids);
	}

	/**
	 * 删除合同管理信息
	 *
	 * @param id 合同管理主键
	 * @return 结果
	 */
	@Override
	public int deleteContractById(String id) {
		return contractMapper.deleteContractById(id);
	}

	/**
	 * 1、判断是否有意向课程。没有则不会转客户
	 * 2、修改商机状态为：7 status、last_update_time
	 * 3、新增客户
	 * @param busId       商机编号
	 * @param contractDTO 信息合同
	 * @return
	 */
	@Override
	public AjaxResult changeContract(Long busId, ContractDTO contractDTO) {
		Business business = iBusinessService.querySubjectByBusId(busId);
		LoginUser loginUser = SecurityUtils.getLoginUser();
		if (Objects.isNull(business.getCourseId())) {
			return AjaxResult.error("商机里面没有选择课程，无法转换客户合同");
		}
		business.setStatus(StatusType.TOCUSTOMER.getValue());
		business.setLastUpdateTime(DateUtils.getNowDate());
		iBusinessService.updateBusiness(business);

		Contract contract = new Contract();
		contract.setId(UUID.randomUUID().toString(true));
		contract.setPhone(contractDTO.getPhone());
		contract.setFileName(contractDTO.getFileName());
		contract.setContractNo(contractDTO.getContractNo());
		contract.setName(business.getName());
		contract.setSubject(business.getSubject());

		contract.setCourseId(business.getCourseId());
		if (Objects.nonNull(business.getCourseId())) {
			Course course = iCourseService.selectCourseById(business.getCourseId());
			contract.setCourseName(course.getName());
			contract.setCoursePrice(course.getPrice().floatValue());
		}
		contract.setChannel(business.getChannel());
		contract.setStatus(StatusType.UNFOLLOWED.getValue());
		contract.setDeptId(loginUser.getDeptId());
		contract.setBusinessId(busId);

		contract.setActivityId(business.getActivityId());
		contract.setDiscountType(DiscountType.NOT_ACTIVITY.getVal());
		contract.setContractOrder(contract.getCoursePrice());
		if (Objects.nonNull(business.getActivityId())) {
			Activity activity = iActivityService.selectActivityById(business.getActivityId());
			contract.setActivityName(activity.getName());
			//折扣
			Float discount = activity.getDiscount();
			//代金券
			Integer vouchers = activity.getVouchers();
			if (Objects.nonNull(discount)) {
				contract.setContractOrder(contract.getCoursePrice() * discount);
				contract.setDiscountType(DiscountType.CLASS_ACTIVITY.getVal());
			} else if (Objects.nonNull(vouchers)) {
				contract.setContractOrder(contract.getCoursePrice() - vouchers);
				contract.setDiscountType(DiscountType.VOUCHER.getVal());
			}
		}
		if(Objects.nonNull(contract.getStatus())){
			//如果订单价格是存在，则表示客户已经购买课程    自己设计：hhj/22/06/27
			contract.setStatus(StatusType.FALSE.getValue());
		}
		contract.setCreateBy(loginUser.getUsername());
		contract.setCreateTime(DateUtils.getNowDate());
		contract.setProcessInstanceId(IpUtils.getHostIp());
		contractMapper.insertContract(contract);
		return AjaxResult.success();
	}

	@Override
	public ContractStatisticsVO contractStatistics(String beginTime, String endTime) {
		List<String> axisLs = getTwoDaysDayDes(beginTime, endTime);
		ContractStatisticsVO contractStatisticsVO = new ContractStatisticsVO();
		contractStatisticsVO.setxAxis(axisLs);

		//beginTime -> endTime 之间的人数  新增客户数   总数
		List<ContractDos> contractCount = contractMapper.selectBetweenTimeCount(beginTime, endTime);
		System.out.println("****************************************contractCount = " + contractCount);
		ContractData contract1 = new ContractData();
		contract1.setName("新增客户数");
		ContractData contract2 = new ContractData();
		contract2.setName("客户总数");

		int sum = 0;
		Map<Integer,Integer> data1 =new HashMap<>();
		Map<Integer,Integer> data2 =new HashMap<>();
		for(ContractDos c : contractCount){
			for(int i =0;i<axisLs.size();i++){
				if(c.getDateTimes().equals(axisLs.get(i))){
					Integer num = Integer.parseInt(c.getNum().toString());
					data1.put(i,num);
					sum += num;
				} else {
					data1.put(i,0);
				}
				data2.put(i,sum);
			}
		}

		List<Integer> newLs1 = new ArrayList<>();
		List<Integer> sumLs = new ArrayList<>();
		if(contractCount.size()==0 || Objects.isNull(contractCount)){
			for (String i : axisLs) {
				newLs1.add(0);
				sumLs.add(0);
			}
		}else {
			newLs1 = data1.values().stream().map(d -> {
				return d.intValue();
			}).collect(Collectors.toList());

			sumLs = data2.values().stream().map(d -> {
				return d.intValue();
			}).collect(Collectors.toList());
		}
		log.info("contractStatistics.data1 = {}" + data1);
		log.info("contractStatistics.data2 = {}" + data2);

		contract1.setData(newLs1);
		contract2.setData(sumLs);
		ArrayList<ContractData> objects = new ArrayList<>();
		objects.add(contract1);
		objects.add(contract2);
		contractStatisticsVO.setSeries(objects);
		return contractStatisticsVO;
	}

	@Override
	public List<SubjectGroupNumDos> subjectStatistics(String beginTime, String endTime) {
		return contractMapper.subjectStatistics(beginTime, endTime);
	}

	@Override
	public ContractStatisticsVO salesStatistics(String beginTime, String endTime) {
		ContractStatisticsVO conVO = new ContractStatisticsVO();
		List<String> axisLs = getTwoDaysDayDes(beginTime, endTime);
		conVO.setxAxis(axisLs);

		ContractData data = new ContractData();
		List<ContractDos> contractDos = contractMapper.selectStatisticsList(beginTime, endTime);
		Map<Integer, Double> resultStorage = new HashMap<>();
		for (ContractDos c : contractDos) {
			for (int i = 0; i < axisLs.size(); i++) {
				if (c.getDateTimes().equals(axisLs.get(i))) {
					Double num = Double.parseDouble(c.getNum().toString());
					resultStorage.put(i,num);
				} else {
					resultStorage.put(i,0.00);
				}
			}
		}
		List<Double> newPrices =
				resultStorage.values().stream().map(r -> r).collect(Collectors.toList());

		data.setData(newPrices);
		data.setName("销售统计");
		conVO.setSeries(Arrays.asList(data));
		return conVO;
	}
}
